#ifndef SERIALMASTER_H
#define SERIALMASTER_H

#include <QObject>
#include <QSerialPortInfo>
#include <QSerialPort>
#include <QTimer>

class SerialMaster : public QObject
{
    Q_OBJECT
public:
    class Info
    {
    public:
        QString name;
        bool isBusy;

        Info() {}
        explicit Info(QString name, bool isBusy)
        {
            this->name = name;
            this->isBusy = isBusy;
        }
    };

    enum Cmd
    {
        Cmd_ReadDoors = 0x01,
        Cmd_OpenDoor,
        Cmd_ReadDoor,
        Cmd_ReadSoftwareVersion,
        Cmd_ReadHardwareVersion,
        Cmd_ReadBuildTime,
        Cmd_OpenAllDoors,
    };

    enum State
    {
        State_Success = 0,
        State_Fail,
        State_TimeOut,
    };

    QSerialPort *serial;
    QTimer *timer;
    quint8 slaveAddr;
    QByteArray rxData;

    typedef void (*Handler)(enum State state, enum Cmd cmd, QByteArray rsp);

    explicit SerialMaster(QObject *parent = nullptr);
    ~SerialMaster();
    QList<Info> availablePorts();
    enum State serialConnect(QString portName);
    void serialDisconnect();
    enum State send(enum Cmd cmd, QByteArray req, Handler handler);
    inline bool isSerialConnected() { return isConnected; }

signals:
    void connectionChanged(bool isConnected);

public slots:

private:
    bool isConnected;
    bool isRxOn;

    QByteArray calcChecksum(QByteArray data);

private slots:
    void receive();
    void onRxTimeout();
};

#endif // SERIALMASTER_H
